<template>
  <Modal
    v-model:active="resultLibraryModalActive"
    transfer
    title="结果库"
    :width="1200"
    confirm-text="确定"
    hide-mask
    draggable
    @confirm="onConfirm"
  >
    <div class="modal-header">
      <div>
        <ButtonGroup shape="button-group">
          <Button shape="button" state="default"
            ><img src="../../assets/icon-back.svg" alt="" class="icon"
          /></Button>
          <Button shape="button" state="default"
            ><img src="../../assets/icon-forward.svg" alt="" class="icon"
          /></Button>
          <Button shape="button" state="default"
            ><img src="../../assets/icon-before.svg" alt="" class="icon"
          /></Button>
          <Button shape="button" state="default"
            ><img src="../../assets/icon-refresh.svg" alt="" class="icon"
          /></Button>
          <Button shape="button" state="default"
            ><img src="../../assets/icon-home.svg" alt="" class="icon"
          /></Button>
        </ButtonGroup>
      </div>
      <Row style="width: 100%; margin-left: 20px" :gap="[16, 0]">
        <Column :span="6">
          <FormItem label="存储空间:">
            <Select
              :options="bucketArr"
              placeholder="请选择存储空间"
              v-model:value="bucketName"
              @change="handleChangeBucket"
            ></Select>
          </FormItem>
        </Column>
        <Column :span="12">
          <FormItem label="初始路径:">
            <Select
              :options="pathArr"
              placeholder="请选择初始路径"
              v-model:value="pathName"
              @change="handleChangePath"
            ></Select>
          </FormItem>
        </Column>
        <Column :span="6">
          <FormItem label="检索对象:">
            <Input
              placeholder="请输入关键字搜索"
              clearable
              :suffix="MagnifyingGlass"
            ></Input>
          </FormItem>
        </Column>
      </Row>
    </div>
    <div class="modal-body">
      <Table
        :columns="columns"
        :data="data"
        highlight
        ref="table"
        @row-check="onRowCheck"
        :height="400"
      >
        <TableColumn
          type="selection"
          id-key="selection"
          :disable-row="(row) => row.isDir"
        />
        <TableColumn name="文件名" id-key="objectName" :order="0">
          <template #default="{ row }">
            <img
              v-if="row.isDir"
              src="../../assets/icon-folder.svg"
              alt=""
              class="icon"
            />
            <a
              v-if="row.isDir"
              @click="onSelectFile(row.objectName)"
              class="file-name"
              >{{ row.objectName }}</a
            >
            <span v-else>{{ row.objectName }}</span>
          </template>
        </TableColumn>
      </Table>
    </div>
    <template #footer>
      <div class="current-path">
        <span>当前位置：</span>
        <Input
          disabled
          style="width: 700px; margin-right: 12px"
          v-model:value="currentPath"
        ></Input>
        <!-- <Button>新建文件夹</Button> -->
      </div>
      <div>
        <Button @click="onClose">取消</Button>
        <Button type="primary" @click="onConfirm">确定</Button>
      </div>
    </template>
  </Modal>
</template>
<script setup lang="ts">
import { defineProps, ref, reactive, onMounted } from "vue";
import { useCoreStore } from "@/UI/store";
import { storeToRefs } from "pinia";
import {
  Row,
  RadioGroup,
  Radio,
  Modal,
  Column,
  FormItem,
  Select,
  Input,
  Table,
  Button,
  TableColumn,
  TableExposed,
  Message,
  ButtonGroup,
} from "cax-ui";
import { MagnifyingGlass } from "@vexip-ui/icons";
import { defineTableColumns } from "cax-ui";
import { getBucketList, getPathList, getObjectList } from "@/UI/api/solver";
import { AppEvent, oss } from "@/UI/config";
const coreStore = useCoreStore();
const bucketName = ref("");
const pathName = ref("");
const currentPath = ref("");
const bucketArr = ref<any>([]);
const pathArr = ref([]);
const data = ref([]);
const table = ref<TableExposed>();
const props = defineProps({
  onSuccess: {
    type: Function,
    default: () => {
      console.log("default onSuccess");
    },
  },
});
const onConfirm = () => {
  const selected = table.value?.getSelected() ?? [];
  if (selected.length > 0) {
    // const tempOssPath = `oss://${bucketName.value}/${selected[0].objectName}`;
    const fullPath = `${oss().endpoint}/${bucketName.value}/${
      selected[0].objectName
    }`;
    coreStore.Notify.next({
      type: AppEvent.RESULT_LIBRARY_SELECTED,
      data: fullPath,
    });
    onClose();
  } else {
    Message.error("请选择文件");
  }
};
const onClose = () => {
  coreStore.updateResultLibraryModalActive(false);
  bucketName.value = "";
  pathName.value = "";
  currentPath.value = "";
  data.value = [];
  table.value?.clearSelected();
};
const columns = reactive(
  defineTableColumns([
    {
      name: "类型/大小",
      key: "size",
    },
  ])
);
let { resultLibraryModalActive } = storeToRefs(useCoreStore());

onMounted(() => {
  getBucketList().then((res) => {
    if (res) {
      if (res?.data?.length > 0) {
        const arr = res.data.map((item: string) => ({
          label: item,
          value: item,
        }));
        bucketArr.value = arr;
      } else {
        bucketArr.value = [
          {
            label: "suanpan-public",
            value: "suanpan-public",
          },
          {
            label: "sh-dc",
            value: "sh-dc",
          },
        ];
      }
    } else {
      bucketArr.value = [];
    }
  });
});

const handleChangeBucket = (value: string) => {
  bucketName.value = value;
  currentPath.value = "";
  pathName.value = "";
  data.value = [];
  getPathList({ bucket: value }).then((res) => {
    if (res) {
      if (res?.data?.length > 0) {
        const arr = res.data.map((item: string) => ({
          label: item,
          value: item,
        }));
        pathArr.value = arr;
      }
    } else {
      pathArr.value = [];
    }
  });
};

const handleChangePath = (value: string) => {
  pathName.value = value;
  console.log({ bucket: bucketName.value, path: value });
  getObjectList({ bucket: bucketName.value, path: value }).then((res) => {
    console.log(res);
    currentPath.value = `oss://${bucketName.value}/${value}`;
    if (res) {
      if (res?.data?.length > 0) {
        data.value = res.data;
      } else {
        data.value = [];
      }
    }
  });
};

const onSelectFile = (objectName: string) => {
  getObjectList({ bucket: bucketName.value, path: objectName }).then((res) => {
    console.log(res);
    currentPath.value = `oss://${bucketName.value}/${objectName}`;
    if (res) {
      if (res?.data?.length > 0) {
        data.value = res.data;
      } else {
        data.value = [];
      }
    }
  });
};

const onRowCheck = (row: any) => {
  table.value?.clearSelected();
  table.value?.selectRow(row.key, true);
};
</script>
<style lang="less" scoped>
.modal-header {
  display: flex;
}
.current-path {
  display: flex;
  flex-direction: row;
  align-content: center;
  justify-content: flex-start;
  align-items: center;
  width: 900px;
  flex: 1;
}
.icon {
  width: 20px;
  height: 20px;
}
.file-name {
  color: inherit; /* 继承父元素的颜色 */
  text-decoration: none; /* 默认去掉下划线 */
}

.file-name:hover {
  color: blue; /* 鼠标悬浮时变蓝 */
  text-decoration: underline; /* 鼠标悬浮时加下划线 */
}
</style>
